import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import {
  Badge,
  Button,
  Card,
  Col,
  Divider,
  Dropdown,
  Form,
  Icon,
  Input,
  InputNumber,
  Menu,
  Modal,
  Radio,
  Row,
  Select,
} from 'antd';
import TableList from '@/components/TableList';
import styles from '../search.less';
import {ipRule, nameMaxLength, remarkMaxLength, ruleP} from '@/utils/rule'
import {decode, encode,} from '@/utils/AesUtil';


const FormItem = Form.Item;
const {TextArea} = Input;
const {Option} = Select;
const RadioGroup = Radio.Group;
const serverTypeMap = [' ', ' '];
const serverType = ['主服务器', '备用服务器'];
const ftpTypeMap = [' ', ' '];
const ftpType = ['FTP', 'SFTP'];
const statusMap = ['success', 'error'];
const status = ['启用', '禁用'];
const formLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 18},
};
const CreateForm = Form.create()(props => {

  const {
    modalVisible,
    form,
    handleAdd,
    handleModalVisible,
    form: {getFieldValue},
    assServer,
    handleTest,
    linkInfo,
    unicodeList,
    setUploading,
    uploading,
  } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  const handleLink = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      setUploading();
      handleTest(fieldsValue);
    });
  }
  return (
    <Modal
      destroyOnClose
      width={800}
      title="新增服务器"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <Row gutter={16}>

        <Col md={12}>
          <FormItem {...formLayout} label="服务器类型">
            {form.getFieldDecorator('isMainFtp', {
              initialValue: '0',
              rules: [{required: true, message: '请选择服务器类型'}],
            })(
              <Radio.Group>
                <Radio value="0">
                  主服务器
                </Radio>
                {/*<Radio value="1">
                  备用服务器
                </Radio>*/}
              </Radio.Group>
            )}
          </FormItem>
        </Col>

        <Col md={12} style={{display: getFieldValue('isMainFtp') === '1' ? 'block' : 'none',}}>
          <FormItem {...formLayout} label="关联服务器">
            {form.getFieldDecorator('mainId', {
              rules: [{required: getFieldValue('isMainFtp') === '1' ? true : false, message: '请选择关联服务器'}],
            })(<Select placeholder="请选择" style={{width: '100%'}}>
              {
                assServer && assServer.length && assServer.map((v) => {
                  return <Option key={v.id} value={v.id}>{v.name}</Option>
                })
              }
            </Select>)}
          </FormItem>
        </Col>

        <Col md={12}>
          <FormItem {...formLayout} label="服务器名称">
            {form.getFieldDecorator('name', {
              rules: [{required: true, message: '服务器名称不能为空'}, {max: 20, message: "字符长度不能超过20"}],
            })(<Input placeholder="请输入"/>)}
          </FormItem>
        </Col>

        <Col md={12}>
          <FormItem {...formLayout} label="IP地址">
            {form.getFieldDecorator('ipAddr', {
              rules: [{required: true, message: 'IP地址不能为空'},
                {pattern: new RegExp(ruleP(3)[0], 'g'), message: ruleP(3)[1]}],
            })(<Input placeholder="请输入"/>)}
          </FormItem>
        </Col>

        <Col md={12}>
          <FormItem {...formLayout} label="端口号">
            {form.getFieldDecorator('port', {
              rules: [{required: true, message: '端口号不能为空'},
                {pattern: new RegExp(ruleP(2)[0], 'g'), message: ruleP(2)[1]}
              ]
            })(<InputNumber placeholder="请输入" min={0} max={65535} step={1} style={{width: '100%'}}/>)}
          </FormItem>
        </Col>
        <Col md={12}>
          <FormItem {...formLayout} label="用户名">
            {form.getFieldDecorator('userCode', {
              rules: [{required: true, message: '用户名不能为空'}, {max: nameMaxLength()[0], message: nameMaxLength()[1]}],
            })(<Input placeholder="请输入"/>)}
          </FormItem>
        </Col>
        <Col md={12}>
          <FormItem {...formLayout} label="密码">
            {form.getFieldDecorator('password', {
              rules: [{required: true, message: '密码不能为空'}],
            })(<Input type="password" placeholder="请输入"/>)}
          </FormItem>
        </Col>

        <Col md={12}>
          <FormItem {...formLayout} label="存储空间">
            {form.getFieldDecorator('diskSize', {
              rules: [{required: true, message: '存储空间不能为空'}],
            })(<InputNumber style={{width: 240}} placeholder="1-100000" min={1} max={100000} step={50}
            />)}
            <span className="ant-form-text">&nbsp;G</span>
          </FormItem>
        </Col>

        <Col md={12}>
          <FormItem {...formLayout} label="FTP类型">
            {form.getFieldDecorator('ftpType', {
              initialValue: "0"
            })(
              <Radio.Group>
                <Radio value="0">
                  FTP
                </Radio>
                <Radio value="1">
                  SFTP
                </Radio>
              </Radio.Group>
            )}
          </FormItem>
        </Col>

        <Col md={12} style={{display: getFieldValue('ftpType') === '1' ? 'none' : 'block',}}>
          <FormItem {...formLayout} label="模式">
            {form.getFieldDecorator('ftpMode', {
              initialValue: "0"
            })(
              <Radio.Group>
                <Radio value="0">
                  主动模式
                </Radio>
                <Radio value="1">
                  被动模式
                </Radio>
              </Radio.Group>
            )}
          </FormItem>
        </Col>

        <Col md={12}>
          <FormItem {...formLayout} label="语言编码">
            {form.getFieldDecorator('unicode', {initialValue: "UTF-8"})(
              <Select placeholder="请选择" style={{width: '100%'}}>
                {
                  unicodeList && unicodeList.map((item, index) => {
                    return (<Option key={index} value={item.value}>{item.name}</Option>)
                  })
                }
              </Select>
            )}
          </FormItem>
        </Col>

        <Col md={24}>
          <FormItem labelCol={{span: 3}} wrapperCol={{span: 21}} label="备注">
            {form.getFieldDecorator('remark', {rules: [{max: remarkMaxLength()[0], message: remarkMaxLength()[1]}]})(
              <TextArea
                style={{minHeight: 32}}
                rows={2}
              />)}
          </FormItem>
        </Col>
        <Col md={4}><Button type="primary" onClick={handleLink}
                            loading={uploading}>{uploading ? '连接中' : '测试连接'}</Button></Col>
        {linkInfo && linkInfo.msg ? (
          <Col md={20} style={{paddingTop: '5px'}}><Icon style={{color: linkInfo.result == 'ok' ? 'green' : '#f5222d'}}
                                                         type={linkInfo.result == 'ok' ? 'check-circle' : 'close-circle-o'}/> {linkInfo.msg}
          </Col>
        ) : null}
      </Row>
    </Modal>
  );
});

@Form.create()
class UpdateForm extends PureComponent {
  static defaultProps = {
    handleUpdate: () => {
    },
    handleUpdateModalVisible: () => {
    },
    values: {},
  };

  constructor(props) {
    super(props);
    this.state = {
      formVals: {
        isMainFtp: props.values.isMainFtp,
        name: props.values.name,
        diskSize: props.values.diskSize,
        ftpType: props.values.ftpType,
        ftpMode: props.values.ftpMode,
        ipAddr: props.values.ipAddr,
        port: props.values.port,
        userCode: props.values.userCode,
        password: props.values.password,
        passwordCheck: props.values.password,
        unicode: props.values.unicode,
        remark: props.values.remark,
        id: props.values.id,
        mainId: props.values.mainId,
        status: props.values.status,
        unicodeList: [],
      },
    };
  }

  //编辑，确定提交
  handleCheck = checkBtn => {
    const {form, handleUpdate, values} = this.props;
    const {formVals: oldValue} = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = {...oldValue, ...fieldsValue};
      this.setState(
        {
          formVals,
        },
        () => {
          handleUpdate(formVals, values);
        }
      );
    });
  };
  renderFooter = checkBtn => {
    const {handleUpdateModalVisible, values} = this.props;
    return [
      <Button key="cancel" onClick={() => handleUpdateModalVisible(false, values)}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleCheck(checkBtn)}>
        确定
      </Button>,
    ];
  };

  handleLink = () => {
    const {handleTest, form, setUploading, values} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      setUploading();
      handleTest(fieldsValue, values);
    });
  }

  render() {
    const {
      updateModalVisible, handleUpdateModalVisible, values, form,
      form: {getFieldValue}, assServer, linkInfo, unicodeList, uploading, Decrypt
    } = this.props;
    const {checkBtn, formVals} = this.state;
    return (
      <Modal
        width={800}
        bodyStyle={{padding: '32px 40px 48px'}}
        destroyOnClose
        title="编辑服务器"
        visible={updateModalVisible}
        footer={this.renderFooter(checkBtn)}
        onCancel={() => handleUpdateModalVisible(false, values)}
        afterClose={() => handleUpdateModalVisible()}
        maskClosable={false}
      >

        <Row gutter={16}>

          <Col md={12}>
            <FormItem id="isMainFtp" {...formLayout} label="服务器类型">
              {form.getFieldDecorator('isMainFtp', {
                rules: [{required: true, message: '请选择服务器类型'}], initialValue: formVals.isMainFtp.toString()
              })(
                <Radio.Group>
                  <Radio value="0">
                    主服务器
                  </Radio>
                  {/*<Radio value="1">
                      备用服务器
                    </Radio>*/}
                </Radio.Group>
              )}
            </FormItem>
          </Col>
          <Col md={12} style={{display: getFieldValue('isMainFtp') === '1' ? 'block' : 'none',}}>
            <FormItem id="mainId" {...formLayout} label="关联服务器">
              {form.getFieldDecorator('mainId', {
                initialValue: formVals.mainId
              })(<Select placeholder="请选择" style={{width: '100%'}}>
                {
                  assServer && assServer.length && assServer.map((v) => {
                    return <Option key={v.id} value={v.id}>{v.name}</Option>
                  })
                }
              </Select>)}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem id="name" {...formLayout} label="服务器名称">
              {form.getFieldDecorator('name', {
                rules: [{required: true, message: '服务器名称不能为空'}, {max: 20, message: "字符长度不能超过20"}],
                initialValue: formVals.name
              })(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem id="ipAddr" {...formLayout} label="IP地址">
              {form.getFieldDecorator('ipAddr', {
                rules: [{required: true, message: 'IP地址不能为空'},
                  {pattern: new RegExp(ruleP(3)[0], 'g'), message: ruleP(3)[1]}
                ], initialValue: formVals.ipAddr
              })(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem id="port" {...formLayout} label="端口号">
              {form.getFieldDecorator('port', {
                rules: [{required: true, message: '端口号不能为空'}, {
                  pattern: new RegExp(ruleP(2)[0], 'g'),
                  message: ruleP(2)[1]
                }], initialValue: formVals.port
              })(<InputNumber placeholder="请输入" min={0} max={65535} style={{width: '100%'}}/>)}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem id="userCode" {...formLayout} label="用户名">
              {form.getFieldDecorator('userCode', {
                rules: [{required: true, message: '用户名不能为空'}, {max: nameMaxLength()[0], message: nameMaxLength()[1]}],
                initialValue: formVals.userCode
              })(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem id="password" {...formLayout} label="密码">
              {form.getFieldDecorator('password', {
                rules: [{required: true, message: '密码不能为空'}], initialValue: formVals.password||'******'
              })(<Input placeholder="请输入" type="password"/>, <Input placeholder="请输入" type="hidden"/>)}
            </FormItem>

            <FormItem id="passwordCheck" style={{display: 'none'}} {...formLayout} label="密码">
              {form.getFieldDecorator('passwordCheck', {initialValue: formVals.passwordCheck||'******'
              })(<Input placeholder="请输入" type="passwordCheck"/>)}

            </FormItem>

          </Col>


          <Col md={12}>
            <FormItem id="diskSize" {...formLayout} label="存储空间">
              {form.getFieldDecorator('diskSize', {
                  rules: [{required: true, message: '存储空间不能为空'}], initialValue: formVals.diskSize
                }
              )(<InputNumber style={{width: 240}} placeholder="1-100000" min={1} max={100000} step={50}
              />)}
              <span className="ant-form-text">&nbsp;G</span>
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem id="ftpType" {...formLayout} label="FTP类型">
              {form.getFieldDecorator('ftpType', {
                initialValue: formVals.ftpType
              })(
                <Radio.Group>
                  <Radio value={0}>
                    FTP
                  </Radio>
                  <Radio value={1}>
                    SFTP
                  </Radio>
                </Radio.Group>
              )}
            </FormItem>
          </Col>

          <Col md={12} style={{display: getFieldValue('ftpType') == "1" ? 'none' : 'block',}}>
            <FormItem id="ftpMode" {...formLayout} label="模式">
              {form.getFieldDecorator('ftpMode', {initialValue: formVals.ftpMode.toString()})(
                <Radio.Group>
                  <Radio value="0">
                    主动模式
                  </Radio>
                  <Radio value="1">
                    被动模式
                  </Radio>
                </Radio.Group>
              )}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem id="unicode" {...formLayout} label="语言编码">
              {form.getFieldDecorator('unicode', {initialValue: formVals.unicode})(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  {
                    unicodeList && unicodeList.map((item, index) => {
                      return (<Option key={index} value={item.value}>{item.name}</Option>)
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="状态">
              {form.getFieldDecorator('status', {
                initialValue: formVals.status
              })(
                <Radio.Group>
                  <Radio value={0}>
                    启用
                  </Radio>
                  <Radio value={1}>
                    禁用
                  </Radio>
                </Radio.Group>
              )}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem id="remark" labelCol={{span: 3}} wrapperCol={{span: 21}} label="备注">
              {form.getFieldDecorator('remark', {
                rules: [{max: remarkMaxLength()[0], message: remarkMaxLength()[1]}],
                initialValue: formVals.remark
              })(
                <TextArea
                  style={{minHeight: 32}}
                  rows={2}
                />)}
            </FormItem>
          </Col>
          <Col md={4}><Button type="primary" onClick={this.handleLink}
                              loading={uploading}>{uploading ? '连接中' : '测试连接'}</Button></Col>
          {linkInfo && linkInfo.msg ? (
            <Col md={20} style={{paddingTop: '5px'}}><Icon
              style={{color: linkInfo.result == 'ok' ? 'green' : '#f5222d'}}
              type={linkInfo.result == 'ok' ? 'check-circle' : 'close-circle-o'}/> {linkInfo.msg}</Col>
          ) : null}
        </Row>
      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ innerFiles, loading }) => ({
  innerFiles,
  loading: loading.models.innerFiles,
}))
@Form.create()
class innerFiles extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    assServer: [], // 关联服务器
    linkInfo: {}, //连接成功后者失败提示信息
    //详情
    detailVisible: false,
    detailsData: {},
    uploading: false,
  };
  columns = [
    {
      title: '服务器名称',
      dataIndex: 'name',
    },
    {
      title: '服务器类型',
      dataIndex: 'isMainFtp',
      render(val) {
        return <Badge status={serverTypeMap[val]} text={serverType[val]} />;
      },
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddr',
    },
    {
      title: 'FTP类型',
      dataIndex: 'ftpType',
      render(val) {
        return ftpType[val];
      },
    },
    {
      title: '已用空间',
      dataIndex: 'usedDiskSize',
      render(val) {
        return (val * 1024).toFixed(2) + 'M';
      },
    },
    {
      title: '总空间',
      dataIndex: 'diskSize',
      render(val) {
        return val + 'G';
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.detailHandelVisible(true, text)}>详情</a>
          <Divider type="vertical" />
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item onClick={() => this.handleUpdateModalVisible(true, record)}>
                  编辑
                </Menu.Item>
                <Menu.Item onClick={() => this.deleteData(text.id)}>删除</Menu.Item>
              </Menu>
            }
          >
            <a>
              更多 <Icon type="down" />
            </a>
          </Dropdown>
        </Fragment>
      ),
    },
  ];

  deleteData = id => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };

  setUploading = () => {
    this.setState({
      uploading: true,
    });
  };

  batchDelete = (rows = []) => {
    const ids = rows
      .map(item => {
        return item.id;
      })
      .join(',');
    this.deleteData(ids); //批量删除
  };
  handleThisRowDelete = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'innerFiles/remove',
      payload: { id },
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
          this.setState({ selectedRows: [] });
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      }, //callback
    });
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.pageList();
    dispatch({
      type: 'innerFiles/unicodeList',
      payload: {
        dataDictTypeCode: 'charset',
      },
      callback: res => {
        if (res.result == 'ok') {
          this.setState({ unicodeList: res.data.dataList });
        }
      },
    }); //语言编码
    dispatch({
      type: 'innerFiles/listFiles',
      payload: { isOutFtp: 0, isMainFtp: 0 },
      callback: res => {
        if (res.result == 'ok') {
          this.setState({
            assServer: res.data.dataList,
          });
        } else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
  }

  // 分页查询列表
  pageList(res, pageSize = 10, pageNum = 0) {
    const { dispatch } = this.props;
    const values = {
      isOutFtp: 0,
      name: res && res.name,
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'innerFiles/queryList',
      payload: values,
      callback: obj => {
        if (obj.result == 'ok' && res.userName) {
          this.treeData(); // 组织树查询
        }
      },
    });
  }

  handleStandardTableChange(pagination) {
    const { formValues } = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState({
        formValues: values,
      });

      this.pageList(values);
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      linkInfo: {},
    });
  };

  detailHandelVisible = (flag, text) => {
    this.setState({
      detailVisible: !!flag,
      detailsData: text,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      stepFormValues: record || {},
      linkInfo: {},
    });
  };

  //测试连接
  handleTest = async (fields, text) => {
    const { dispatch } = this.props;

    //密码这儿特殊处理一下
    let passwordCheck = fields.passwordCheck;
    let password = fields.password;
    let lastpassword = password==='******'||await encode(password);
    if (passwordCheck && password) {
      //如果两个相等，表示密码没有修改，并且是加密的
      if (passwordCheck == password) {
        lastpassword = password;
      }
    }

    dispatch({
      type: 'innerFiles/test',
      payload: {
        id: (text && text.id) || '',
        isOutFtp: 0,
        isMainFtp: fields.isMainFtp,
        mainId: fields.mainId,
        name: fields.name,
        diskSize: fields.diskSize,
        ftpType: fields.ftpType,
        ftpMode: fields.ftpMode,
        ipAddr: fields.ipAddr,
        port: fields.port,
        userCode: fields.userCode,
        password:lastpassword==='******'?null:await encode(password),
        unicode: fields.unicode,
        remark: fields.remark,
        status: fields.status,
      },
      callback: res => {
        this.setState({
          linkInfo: res,
          uploading: false,
        });
      },
    });
  };

  encData = async word => {
    let encPassword = await encode(word);
    return encPassword;
  };

  // 解密方法
  Decrypt = async word => {
    const decodeStr = await decode(word);
    return decodeStr;
  };

  //新增
  handleAdd = async fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'innerFiles/add',
      payload: {
        isOutFtp: 0,
        isMainFtp: fields.isMainFtp,
        mainId: fields.mainId,
        name: fields.name,
        diskSize: fields.diskSize,
        ftpType: fields.ftpType,
        ftpMode: fields.ftpMode,
        ipAddr: fields.ipAddr,
        port: fields.port,
        userCode: fields.userCode,
        // password: this.encData(fields.password),
        password: await encode(fields.password),
        unicode: fields.unicode,
        remark: fields.remark,
        status: fields.status,
      },
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({
            title: res.msg,
          });
          dispatch({
            type: 'innerFiles/queryList',
            payload: { isOutFtp: 0 },
          });
        } else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      }, //callback
    });
    this.handleModalVisible();
  };

  //编辑
  handleUpdate = async (fields, value) => {
    const { dispatch } = this.props;

    //密码这儿特殊处理一下
    let passwordCheck = fields.passwordCheck;
    let password = fields.password;

    let lastpassword = password==='******'||await encode(password);
    if (passwordCheck && password) {
      //如果两个相等，表示密码没有修改，并且是加密的
      if (passwordCheck == password) {
        lastpassword = password;
      }
    }

    dispatch({
      type: 'innerFiles/update',
      payload: {
        isOutFtp: 0,
        isMainFtp: fields.isMainFtp,
        mainId: fields.mainId,
        name: fields.name,
        diskSize: fields.diskSize,
        ftpType: fields.ftpType,
        ftpMode: fields.ftpMode,
        ipAddr: fields.ipAddr,
        port: fields.port,
        userCode: fields.userCode,
        password: lastpassword==='******'?null:await encode(password),
        unicode: fields.unicode,
        remark: fields.remark,
        id: fields.id,
        status: fields.status,
      },
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({
            title: res.msg,
          });
          dispatch({
            type: 'innerFiles/queryList',
            payload: { isOutFtp: 0 },
          });
        } else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      }, //callback
    });

    this.handleUpdateModalVisible();
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="服务器名称">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      innerFiles: { data },
      loading,
      form,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      stepFormValues,
      assServer,
      linkInfo,
      detailVisible,
      detailsData,
      unicodeList,
      uploading,
    } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      handleTest: this.handleTest,
      setUploading: this.setUploading,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
      handleTest: this.handleTest,
      setUploading: this.setUploading,
      Decrypt: this.Decrypt,
    };

    const detailsMethods = {
      detailHandelVisible: this.detailHandelVisible,
    };

    return (
      <Card bordered={false}>
        <CreateForm
          {...parentMethods}
          modalVisible={modalVisible}
          assServer={assServer}
          linkInfo={linkInfo}
          unicodeList={unicodeList}
          uploading={uploading}
        />
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
              </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange.bind(this)}
            rowKey={record => record.id}
          />
        </div>
        {updateModalVisible && stepFormValues && Object.keys(stepFormValues).length ? (
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={stepFormValues}
            assServer={assServer}
            linkInfo={linkInfo}
            unicodeList={unicodeList}
            uploading={uploading}
          />
        ) : null}
        {detailsData && detailsData.id ? (
          <Details
            {...detailsMethods}
            detailVisible={detailVisible}
            form={form}
            detailsData={detailsData}
          />
        ) : null}
      </Card>
    );
  }
}

class Details extends PureComponent {

  render() {
    const {detailVisible, detailHandelVisible, form, detailsData} = this.props;
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看详情"
        visible={detailVisible}
        onOk={() => detailHandelVisible()}
        onCancel={() => detailHandelVisible()}
        footer={[
          <Button key="back" type="primary" onClick={() => detailHandelVisible()}>返回</Button>
        ]}
        className={styles.viewMore}
      >
        <Row>

          <Col md={12}>
            <FormItem {...formLayout} label="服务器类型">
              {detailsData.isMainFtp == 0 ? '主服务器' : '备用服务器'}
            </FormItem>
          </Col>

          {/*          <Col md={12} style={{display: detailsData.isMainFtp == 1 ? 'block' : 'none',}}>
            <FormItem {...formLayout} label="关联服务器">
              {detailsData.mainName}
            </FormItem>
          </Col>*/}
          <Col md={12}>
            <FormItem {...formLayout} label="服务器名称">
              {detailsData.name}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="IP地址">
              {detailsData.ipAddr}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="端口号">
              {detailsData.port}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="用户名">
              {detailsData.userCode}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="存储空间">
              {detailsData.diskSize}G
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="FTP类型">
              {detailsData.ftpType == 0 ? 'FTP' : 'SFTP'}
            </FormItem>
          </Col>

          <Col md={12} style={{display: detailsData.ftpType == 1 ? 'none' : 'block',}}>
            <FormItem {...formLayout} label="模式">
              {detailsData.ftpMode == 0 ? '主动模式' : '被动模式'}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="状态">
              {detailsData.status == 0 ? '启用' : '禁用'}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="语言编码">
              {detailsData.unicode}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem labelCol={{span: 3}} wrapperCol={{span: 21}} label="备注">
              {detailsData.remark}
            </FormItem>
          </Col>
        </Row>
      </Modal>
    );
  }
}

export default innerFiles;
